package com.etheart.framework.core.config;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderSupport;
import org.springframework.stereotype.Service;

import com.etheart.framework.core.FrameworkCoreException;

@Service("etheart_ConfigService")
public class ConfigServiceImpl extends PropertiesLoaderSupport implements ConfigService, InitializingBean, ApplicationContextAware{
	private ApplicationContext applicationContext;

	private Properties properties = new Properties();

	public String getValueByKey(String key) {
		return properties.getProperty(key);
	}

	public void afterPropertiesSet() {
		String[] beanNames = applicationContext.getBeanNamesForType(PropertyPlaceholderConfigurer.class);
		if (beanNames ==null || beanNames.length == 0){
			return;
		}
		try {
			for (String beanName : beanNames) {
				PropertyPlaceholderConfigurer configurer = applicationContext
						.getBean(beanName, PropertyPlaceholderConfigurer.class);
				this.setLocations(this.getLocations(configurer));
				this.loadProperties(properties);
			}
		} catch (IOException e) {
			throw new FrameworkCoreException("Failed to load properties configuration file", e);
		} catch (IllegalAccessException e) {
			throw new FrameworkCoreException("Failed to load properties configuration file", e);
		}
	}

	private Resource[] getLocations(PropertyPlaceholderConfigurer configurer) throws IllegalAccessException{
		Field[] fields = PropertiesLoaderSupport.class.getDeclaredFields();
		for (Field field : fields) {
			if (StringUtils.equals(field.getName(), "locations")) {
				field.setAccessible(true);
				Resource[] locations = (Resource[]) field.get(configurer);
				return locations;
			}
		}
		return null;
	}

	public int getIntegerValueByKey(String key) {
		String value = this.getValueByKey(key);
		return  NumberUtils.toInt(value);
	} 

	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}
}
